import { myRequest } from './request.js';

const BASE_URL = "http://localhost:9001";
const URL = 'http://localhost:8004';
const IMAGE_SERVER_URL = "http://localhost:8086";
// 确认BASE1是否与后端服务端口一致
const BASE1 = "http://localhost:1000"; // 确保后端服务运行在该端口
const NEARBY_SERVICE_URL = "http://localhost:8087"; // zhentao-Nearby服务端口
const AI_SERVICE_URL = "http://localhost:8080"; // AI客服服务端口
// 默认请求头
const DEFAULT_HEADERS = {
  'Content-Type': 'application/json'
};






// 获取轮播图数据
const getCarouselList = () => {
  return myRequest({
    url: `${BASE_URL}/us/list`,
    method: 'GET'
  });
};

// 获取活动列表
const getActivityList = () => {
  return myRequest({
    url: `${BASE_URL}/us/list2`,
    method: 'GET'
  });
};

// 获取活动详情
const getActivityDetail = (id) => {
  return myRequest({
    url: `${BASE_URL}/us/listId`,
    method: 'GET',
    data: { id }
  });
};

// 测试后端连接
const testBackendConnection = () => {
  return myRequest({
    url: `${BASE_URL}/us/list2`,
    method: 'GET'
  });
};

// 用户签到
const userSignIn = (userId) => {
  console.log('签到API调用，用户ID:', userId);
  return myRequest({
    url: `${BASE_URL}/us/sign`,
    method: 'POST',
    header: {
      ...DEFAULT_HEADERS,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: { userId }
  });
};

// 获取用户签到统计
const getUserSignCount = (userId) => {
  console.log('获取签到统计API调用，用户ID:', userId);
  return myRequest({
    url: `${BASE_URL}/us/sign/count`,
    method: 'GET',
    header: DEFAULT_HEADERS,
    data: { userId }
  });
};







// 博客相关API
const getBlogList = () => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/findAll`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 根据userId获取博客详情
const getBlogByUserId = (userId) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/findById`,
    method: 'GET',
    header: DEFAULT_HEADERS,
    data: { userId }
  });
};

// 根据博客ID获取博客详情
const getBlogById = (id) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/findById`,
    method: 'GET',
    header: DEFAULT_HEADERS,
    data: { Id: id }
  });
};

// 发布博客
const postBlog = (blogData) => {
  console.log('发送博客数据到后端:', blogData);
  
  // 确保images字段不超过数据库限制
  if (blogData.images && blogData.images.length > 100) {
    blogData.images = blogData.images.substring(0, 100);
  }
  
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/add`,
    method: 'POST',
    header: {
      'Content-Type': 'application/json'
    },
    data: blogData
  });
};

// 点赞博客
const likeBlog = (blogId, userId) => {
  console.log('调用点赞API，参数:', { blogId, userId });
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/likes/${blogId}?userId=${userId || ''}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 检查博客点赞状态
const checkBlogLikeStatus = (blogId, userId) => {
  console.log('检查博客点赞状态，参数:', { blogId, userId });
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/isLiked/${blogId}?userId=${userId || ''}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 评论博客
const commentBlog = (blogId, content) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/comment`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: { 
      blogId,
      content 
    }
  });
};

// 用户相关API
const getUserInfo = (userId) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/user/info/${userId}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 微信登录API
const wxLogin = (code, wxHeadPic, wxUsername) => {
  return myRequest({
    url: `${BASE1}/app/user/wx_login`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: { 
      code,
      wxHeadPic,
      wxUsername
    }
  });
};

// 获取当前登录用户信息 - 直接返回缓存中的用户数据，不调用后端接口
const getLoginUser = (token) => {
  // 这里直接返回一个Promise，因为后端实际没有这个接口
  return new Promise((resolve, reject) => {
    try {
      // 可以在这里添加一些验证逻辑，例如检查token是否存在
      if (!token) {
        reject({ code: -1, msg: "未登录" });
        return;
      }
      // 模拟成功响应
      resolve({ 
        data: { 
          code: 0, 
          msg: "获取用户信息成功" 
          // 注意：这里实际上没有用户数据，因为后端没有接口返回
          // 前端应该在登录成功后存储用户信息
        } 
      });
    } catch (error) {
      reject(error);
    }
  });
};

// 用户退出登录
const logout = (token) => {
  return myRequest({
    url: `${BASE1}/app/user/logout`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: { token }
  });
};

// 更新用户信息
const updateUserInfo = (userData) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/app/user/update`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: userData
  });
};

// 图片上传
const uploadPhoto = (photoBase64) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/photo/app_upload`,
    method: 'POST',
    header: {
      'Content-Type': 'application/json'
    },
    data: { 
      photoBase64: photoBase64 
    }
  });
};

// 更新订单状态
const updateOrderState = (id, state) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/app/order/update`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: { id, state }
  });
};

// 删除评论
const removeComment = (id) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/app/comment/remove`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: { id }
  });
};

// 删除博客
const deleteBlog = (id) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/delete`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: { id }
  });
};

// 图片访问路径
const getImageUrl = (filename) => {
  if (!filename) return '';
  
  // 如果已经是完整URL，则直接返回
  if (filename.startsWith('http')) {
    return filename;
  }
  
  // 否则构建完整的图片URL
  return `${IMAGE_SERVER_URL}/${filename}`;
};
// 获取附近的人（调用后端 zhentao-Nearby 服务的 /nearby/of/type 接口）
// 以键值对方式传输数据
const getNearbyPeople = (params) => {
  console.log('API层发送键值对参数:', params);
  return myRequest({
    url: `${NEARBY_SERVICE_URL}/nearby/of/type`,
    method: 'GET',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: params
  });
};

// 获取用户相册
const getUserAlbum = (userId) => {
  return myRequest({
    url: `${IMAGE_SERVER_URL}/blog/findUserById`,
    method: 'GET',
    header: DEFAULT_HEADERS,
    data: { id: userId }
  });
};

// 实名认证API
const verifyIdentity = (realName, idCard, userId) => {
  console.log('调用实名认证API，参数:', { realName, idCard, userId });
  return myRequest({
    url: `${BASE_URL}/rz/rz`,
    method: 'POST',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
      name: realName,
      card: idCard,
      userId: userId // 添加用户ID参数
    }
  });
};

// 查询实名认证状态
const getVerificationStatus = (userId) => {
  console.log('查询实名认证状态，用户ID:', userId);
  return myRequest({
    url: `${BASE_URL}/rz/status`,
    method: 'GET',
    data: { userId }
  });
};

// 检查实名认证状态（用于状态卡片）
const checkVerificationStatus = (userId) => {
  const params = userId ? { userId } : {};
  return myRequest({
    url: `${BASE_URL}/rz/check-status`,
    method: 'GET',
    data: params
  });
};

// 检查会员状态
const checkMemberStatus = () => {
  return myRequest({
    url: `${BASE_URL}/member/status`,
    method: 'GET'
  });
};

// 开通会员
const activateMember = (params) => {
  return myRequest({
    url: `${BASE_URL}/member/activate`,
    method: 'POST',
    data: params
  });
};

// 获取红娘信息 - 修复箭头函数定义
const getMatchmakerInfo = () => {
  return myRequest({
    url: `${BASE_URL}/matchmaker/find`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 获取所有红娘列表
const getMatchmakerList = () => {
  return myRequest({
    url: `${BASE_URL}/matchmaker/find`,  // 修改为与getMatchmakerInfo相同的URL
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 添加红娘
const addMatchmaker = (username, images, phone) => {
  console.log('添加红娘API调用参数:', { username, images, phone });
  return myRequest({
    url: `${BASE_URL}/matchmaker/add`,
    method: 'POST',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: { 
      username,  // 后端参数名是username
      images,    // 后端参数名是images
      phone      // 后端参数名是phone
    }
  });
};

// 申请成为红娘
const applyMatchmaker = (userId, reason) => {
  return myRequest({
    url: `${BASE_URL}/matchmaker/apply`,
    method: 'POST',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: { 
      userId,
      reason
    }
  });
};


// 二维码相关API
// 生成用户推广二维码
const generateUserQrCode = (userId) => {
  return myRequest({
    url: `${URL}/api/promotion/qrcode/generate/${userId}`,
    method: 'POST',
    header: DEFAULT_HEADERS
  });
};

// 生成带场景的用户推广二维码
const generateUserQrCodeWithScene = (userId, scene) => {
  return myRequest({
    url: `${URL}/api/promotion/qrcode/generate`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: {
      userId: userId,
      scene: scene
    }
  });
};

// 获取用户二维码
const getUserQrCode = (userId) => {
  return myRequest({
    url: `${URL}/api/promotion/qrcode/${userId}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 解码邀请码
const decodeInviteCode = (inviteCode) => {
  return myRequest({
    url: `${URL}/api/promotion/decode/${inviteCode}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};
// 分销提成相关API
// 计算提成
const calculateCommission = (parentUserId, childUserId, amount, memberType) => {
  return myRequest({
    url: `${URL}/api/commission/calculate/${parentUserId}/${childUserId}/${amount}/${memberType}`,
    method: 'POST',
    header: DEFAULT_HEADERS
  });
};
// 记录提成
const recordCommission = (record) => {
  return myRequest({
    url: `${URL}/api/commission/record`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: record
  });
};

// 获取用户的提成记录
const getCommissionRecords = (userId) => {
  return myRequest({
    url: `${URL}/api/commission/records/${userId}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 获取用户的总提成金额
const getTotalCommission = (userId) => {
  return myRequest({
    url: `${URL}/api/commission/total/${userId}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};
// 获取提成比例配置
const getCommissionRatio = (userType, memberType) => {
  return myRequest({
    url: `${URL}/api/commission/ratio/${userType}/${memberType}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 设置提成比例
const setCommissionRatio = (userType, memberType, ratio) => {
  return myRequest({
    url: `${URL}/api/commission/ratio/${userType}/${memberType}/${ratio}`,
    method: 'POST',
    header: DEFAULT_HEADERS
  });
};

// 用户关系相关API
// 绑定下级用户
const bindSubordinateUser = (parentUserId, childUserId) => {
  return myRequest({
    url: `${URL}/api/user-relation/bind`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: {
      parentUserId: parentUserId,
      childUserId: childUserId
    }
  });
};

// 获取下级用户列表
const getSubordinateUsers = (parentUserId) => {
  return myRequest({
    url: `${URL}/api/user-relation/subordinates/${parentUserId}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 获取上级用户
const getParentUser = (childUserId) => {
  return myRequest({
    url: `${URL}/api/user-relation/parent/${childUserId}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 获取用户层级
const getUserLevel = (userId) => {
  return myRequest({
    url: `${URL}/api/user-relation/level/${userId}`,
    method: 'GET',
    header: DEFAULT_HEADERS
  });
};

// 检查是否为下级用户
const isSubordinateUser = (parentUserId, childUserId) => {
  return myRequest({
    url: `${URL}/api/user-relation/check`,
    method: 'GET',
    header: DEFAULT_HEADERS,
    data: {
      parentUserId: parentUserId,
      childUserId: childUserId
    }
  });
};

// 解绑下级用户
const unbindSubordinateUser = (parentUserId, childUserId) => {
  return myRequest({
    url: `${URL}/api/user-relation/unbind`,
    method: 'POST',
    header: DEFAULT_HEADERS,
    data: {
      parentUserId: parentUserId,
      childUserId: childUserId
    }
  });
};

// AI客服聊天
const sendCustomerServiceMessage = (message, userId) => {
  return myRequest({
    url: `${AI_SERVICE_URL}/api/customer-service/chat`,
    method: 'POST',
    data: {
      message: message,
      userId: userId
    }
  });
};

// 获取用户提现记录（按时间倒序）
const getWithdrawalRecordsByUserId = (userId) => {
  return myRequest({
    url: `${BASE_URL}/withdrawal/list`,
    method: 'GET',
    header: DEFAULT_HEADERS,
    data: { userId }
  });
};

// 提现申请
const applyWithdraw = (userId, amount, bankCard, bankName, realName) => {
  return myRequest({
    url: `${BASE_URL}/withdrawal/apply`,
    method: 'POST',
    header: {
      'Content-Type': 'application/json'
    },
    data: {
      userId,
      amount,
      bankCard,
      bankName,
      realName
    }
  });
};

// 获取用户余额信息
const getUserBalance = (userId) => {
  return myRequest({
    url: `${BASE_URL}/withdrawal/balance`,
    method: 'GET',
    header: DEFAULT_HEADERS,
    data: { userId }
  });
};
export default {
  BASE_URL,
  BASE1,
  IMAGE_SERVER_URL,

  getCarouselList,
  getActivityList,
  getActivityDetail,
  testBackendConnection,
  getBlogList,
  getBlogByUserId,
  getBlogById,
  postBlog,
  likeBlog,
  checkBlogLikeStatus,
  commentBlog,
  getUserInfo,
  wxLogin,
  getLoginUser,
  logout,
  updateUserInfo,
  uploadPhoto,
  updateOrderState,
  removeComment,
  getImageUrl,
  getNearbyPeople,
  getUserAlbum,
  userSignIn,
  getUserSignCount,
  deleteBlog,
  verifyIdentity,
  getVerificationStatus,
  checkVerificationStatus,
  checkMemberStatus,
  activateMember,
  getMatchmakerInfo,
  getMatchmakerList,
  applyMatchmaker,
  addMatchmaker,
  generateUserQrCode,
  generateUserQrCodeWithScene,
  getUserQrCode,
  decodeInviteCode,
  recordCommission,
  getCommissionRecords,
  getTotalCommission,
  getCommissionRatio,
  setCommissionRatio,
  bindSubordinateUser,
  getSubordinateUsers,
  getParentUser,
  getUserLevel,
  isSubordinateUser,
  unbindSubordinateUser,
  calculateCommission,
  sendCustomerServiceMessage,
  getWithdrawalRecordsByUserId,
  applyWithdraw,
  getUserBalance
};